<!DOCTYPE html>
<html>

<head>
    <title>Vue2 原生路由示例</title>
    <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script> -->
    <script src="./lib/npm/vue/dist/vue.min.js"></script>
</head>

<body>
    <div id="app">
        <div class="nav">
            <a href="#/home" @click.prevent="navigateTo('/home')">首页</a>
            <a href="#/about" @click.prevent="navigateTo('/about')">关于</a>
            <a href="#/contact" @click.prevent="navigateTo('/contact')">联系</a>
        </div>

        <component :is="currentComponent"></component>
    </div>

    <script>
        // 定义路由组件
        const Home = {
            template: `<div><h2>首页内容</h2><p>欢迎来到首页！</p></div>`
        };

        const About = {
            template: `<div><h2>关于我们</h2><p>这是关于页面</p></div>`
        };

        const Contact = {
            template: `<div><h2>联系我们</h2><p>联系方式: contact@example.com</p></div>`
        };

        const NotFound = {
            template: `<div><h2>404 页面未找到</h2></div>`
        };

        // 路由配置
        const routes = {
            '/home': Home,
            '/about': About,
            '/contact': Contact
        };

        // 创建 Vue 实例
        new Vue({
            el: '#app',
            data: {
                currentRoute: window.location.hash.slice(1) || '/home'
            },
            computed: {
                currentComponent() {
                    return routes[this.currentRoute] || NotFound
                }
            },
            methods: {
                navigateTo(route) {
                    window.location.hash = route
                }
            },
            created() {
                // 监听 hashchange 事件
                window.addEventListener('hashchange', () => {
                    this.currentRoute = window.location.hash.slice(1)
                    console.log('this.currentRoute', this.currentRoute)
                });

                // 初始化时处理 hash
                if (!window.location.hash) {
                    window.location.hash = '#/home'
                }
            }
        });
    </script>

    <style>
        .nav {
            margin-bottom: 20px;
            padding: 10px;
            background: #f0f0f0;
        }

        .nav a {
            margin-right: 15px;
            text-decoration: none;
            color: #333;
        }

        .nav a:hover {
            color: #007bff;
        }

        h2 {
            color: #333;
        }
    </style>
</body>

</html>